#include "netport.h"

#include "data/mycachedata.h"
#include "data/receivedata.h"
#include "data/myfunc.h"
#include "script/MyScript.h"

#include <QTcpSocket>
#include <QScriptValueList>
#include <QMutexLocker>
#include <QDebug>

////////////////////////////////////////////////////////////

//static val
float  NetPort::FLIMIT = float(0.0000001);

NetPort::NetPort(int gid
                 , NetArg _netarg
                 , ProtocolDef _protodefs
                 , QList<PInfo> _pinfos
                 , int _controlsleep
                 , QObject*parent)
    : QThread(parent)
    , gatherID(gid)
    , netarg(_netarg)
    , protodefs(_protodefs)
    , running(true)
    , m_csocket(NULL)
{
    mycachedata = MyCacheData::getInstance();
    ptr_ReceiveData = ReceiveData::getInstance();
    //
    m_NetState.linkTime = mycachedata->getSec()-3;
    m_NetState.heartTime = mycachedata->getSec();
    m_NetState.netPortStateTime = mycachedata->getSec()+100;
    //
    allCallTime = mycachedata->getUsec();
    //建立本采集组下地址点与编号点映射
    for (QList<PInfo>::iterator it = _pinfos.begin(); it != _pinfos.end(); it++)
    {
        it->updateTime = mycachedata->getSec();
        it->sendTime = mycachedata->getSec();
        addr_to_ids[it->addr] = (*it);
        id_to_addrs[it->id] = (*it);
    }
    myScr = new MyScript(protodefs.jsfile);
    allCallCmdInit(cmds);
    cmds.time_interval = _controlsleep;
    limitSize = 2*cmds.cmd_totalcall.size()+2;
}

NetPort::~NetPort()
{
    running=false;
    try{
        this->terminate();
        this->wait();
        qInfo() << "NetPort::destroy\n";
    }catch(...){
        qDebug() << "NetPort::destroy fail\n";
    }
}

void NetPort::run()
{
    initTcpSocket();
    qRegisterMetaType<QAbstractSocket::SocketError>("MySocketError");
    qint64 curTime = mycachedata->getUsec();
    qInfo() << "NetPort::run and initTcpSocket";
    while (running) {
        this->checkLink();
        curTime = mycachedata->getUsec();
        if((allCallTime+cmds.time_interval)<curTime){
            allCallTime = curTime;
            allCall();
        }
        this->doCmd();
        this->checkReadyRead();
        this->msleep(10);
    }
    try{
        destroyTcpSocket();
        qInfo() << "NetPort::destroyTcpSocket";
    }catch(...){
        qDebug() << "NetPort::destroyTcpSocket fail";
    }
    exec();
};

void NetPort::allCall()
{
    for(int i=0; i<cmds.cmd_totalcall.size(); i++){
//        this->writeMsg((const char*)cmds.cmd_totalcall[i].toStdString().c_str()
//                       ,cmds.cmd_totalcall[i].length(),true);
        AddCmd((unsigned char*)cmds.cmd_totalcall[i].toStdString().c_str(),cmds.cmd_totalcall[i].length(),true);
    }
};

void NetPort::AddCmd(unsigned char*cmd, int len,bool uf,bool allCallf)
{
    QMutexLocker locker(&netcms_mutex);
    if(netcms.size()>limitSize&&allCallf)
        return;
    NetCmd ncmd(cmd,len,uf);
    allCallf?netcms.enqueue(ncmd):netcms.prepend(ncmd);
}

bool NetPort::getFirstCmd(NetCmd &ncmd)
{
    QMutexLocker locker(&netcms_mutex);
    if(netcms.empty())
        return false;
    ncmd = netcms.dequeue();
    return true;
}

void NetPort::doCmd()
{
    NetCmd ncmd;
    if(getFirstCmd(ncmd))
    {
        writeMsg((unsigned char*)ncmd.Buf,ncmd.len,ncmd.u16f);
    }
};

void NetPort::allCallCmdInit(CMDLib &_cmds)
{
    try{
        QScriptValueList args;
        myScr_Mutex.lock();
        QString retVal = myScr->myFunc("getTotalCallCMD",args).toString();
        myScr_Mutex.unlock();
        if(!retVal.isEmpty()){
            QStringList cmdsDesc = retVal.split(';',QString::SkipEmptyParts);
            for(int i=0; i<cmdsDesc.size(); i++){
                QStringList cmds = cmdsDesc.at(i).split(',',QString::SkipEmptyParts);
                if(2==cmds.size()){
                    int type = cmds[1].trimmed().toInt();
                    switch(type){
                    case 0:
                        _cmds.cmd_totalcall.append(cmds[0].trimmed());
                        break;
                    case 1:
                    {
                        QString _cmd = cmds[0].trimmed();
                        //CRC校验
                        unsigned char bufCRC[256] = { 0 };
                        int rlen = PFunc::string2bytes(_cmd.toStdString().c_str(), bufCRC, _cmd.length());
                        unsigned int crc = PFunc::crc16(bufCRC, rlen);
                        unsigned char bufCMD[256] = { 0 };
                        sprintf((char*)bufCMD, "%s%02X%02X", _cmd.toStdString().c_str(), (crc & 0XFF), ((crc >> 8) & 0XFF));
                        _cmd = QString::fromLocal8Bit((const char*)bufCMD);
                        _cmds.cmd_totalcall.append(_cmd);
                    }
                        break;
    //                case 2:
    //                    break;
                    default:
                        _cmds.cmd_totalcall.append(cmds[0].trimmed());
                        break;
                    }
                }
            }
        }
    }catch(...){
        qDebug() << "NetPort::allCallCmdInit Exception";
    }
}

bool NetPort::initTcpSocket()
{
    try{
        if(NULL==m_csocket){
            m_csocket = new QTcpSocket();
            connect(m_csocket,SIGNAL(readyRead()),this,SLOT(readData()));
            connect(m_csocket, &QTcpSocket::disconnected, m_csocket, &QTcpSocket::deleteLater);
            connect(m_csocket,SIGNAL(error(QAbstractSocket::SocketError))
                    ,this,SLOT(sockeError(QAbstractSocket::SocketError)));
            return true;
        }
        return false;
    }catch(...){
        qDebug() << "NetPort::initTcpSocket Exception";
        return false;
    }
}

bool NetPort::destroyTcpSocket()
{
    try{
        if(NULL!=m_csocket){
            disconnect(m_csocket,SIGNAL(readyRead()),this,SLOT(readData()));
            disconnect(m_csocket, &QTcpSocket::disconnected, m_csocket, &QTcpSocket::deleteLater);
            disconnect(m_csocket,SIGNAL(error(QAbstractSocket::SocketError))
                    ,this,SLOT(sockeError(QAbstractSocket::SocketError)));
            m_NetState.linking = !disconnectMyHost();
            m_NetState.ativity = false;
            delete m_csocket;
            m_csocket = NULL;   
        }
    }catch(...){
        qDebug() << "NetPort::destroyTcpSocket Exception";
        return false;
    }
    return true;
}

bool NetPort::connectMyHost()
{
    try{
        if(NULL==m_csocket){
            return false;
        }
        if(QAbstractSocket::UnconnectedState==m_csocket->state()){
            m_csocket->connectToHost(netarg.ipStr,netarg.port,QIODevice::ReadWrite);
            if(m_csocket->waitForConnected()){
                qInfo() << QString("NetPort::success connect to host(%1:%2)")
                            .arg(netarg.ipStr).arg(netarg.port);

                logNotify(QString("NetPort::success connect to host(%1:%2)")
                          .arg(netarg.ipStr).arg(netarg.port));
                m_NetState.ativity = true;
                m_NetState.m_rf = true;
                m_NetState.m_wf = true;
                m_NetState.m_tc = true;
                return true;
            }else{
                qWarning() << QString("NetPort::connect to host(%1:%2) fail!")
                            .arg(netarg.ipStr).arg(netarg.port);
                return false;
            }
        }else if(QAbstractSocket::ConnectedState==m_csocket->state()){
            return true;
        }else{
            return false;
        }
    }catch(...){
        qDebug() << "NetPort::connectMyHost Exception";
        return false;
    }
}

bool NetPort::disconnectMyHost()
{
    try{
        if(NULL==m_csocket){
            return true;
        }
        if(QAbstractSocket::ConnectedState==m_csocket->state()){
            m_csocket->disconnectFromHost();
            if(m_csocket->waitForDisconnected())
            {
                qInfo() << QString("NetPort::disconnect to host(%1:%2)")
                            .arg(netarg.ipStr).arg(netarg.port);
                logNotify(QString("NetPort::disconnect to host(%1:%2)")
                          .arg(netarg.ipStr).arg(netarg.port));
                m_NetState.ativity = false;
                m_NetState.m_rf = false;
                m_NetState.m_wf = false;
                m_NetState.m_tc = false;
                return true;
            }else{
                qWarning() << QString("NetPort::disconnect to host(%1:%2) fail!")
                            .arg(netarg.ipStr).arg(netarg.port);
                return false;
            }
        }else if(QAbstractSocket::UnconnectedState==m_csocket->state()){
            return true;
        }else{
            return false;
        }
    }catch(...){
        qDebug() << "NetPort::disconnectMyHost Exception";
        return true;
    }
}

void NetPort::sockeError(QAbstractSocket::SocketError error)
{
    if(NULL==m_csocket)
        return;
    switch (error) {
    case QAbstractSocket::ConnectionRefusedError:
        break;
    case QAbstractSocket::RemoteHostClosedError:
        break;
    case QAbstractSocket::HostNotFoundError:
        break;
    case QAbstractSocket::SocketAccessError:
        break;
    case QAbstractSocket::SocketResourceError:
        break;
    case QAbstractSocket::SocketTimeoutError:
        return;//超时不处置
    case QAbstractSocket::DatagramTooLargeError:
        break;
    case QAbstractSocket::NetworkError:
        break;
    case QAbstractSocket::AddressInUseError:
        break;
    case QAbstractSocket::SocketAddressNotAvailableError:
        break;
    case QAbstractSocket::UnsupportedSocketOperationError:
        break;
    case QAbstractSocket::ProxyAuthenticationRequiredError:
        break;
    case QAbstractSocket::SslHandshakeFailedError:
        break;
    case QAbstractSocket::UnfinishedSocketOperationError:
        break;
    case QAbstractSocket::ProxyConnectionRefusedError:
        break;
    case QAbstractSocket::ProxyConnectionClosedError:
        break;
    case QAbstractSocket::ProxyConnectionTimeoutError:
        break;
    case QAbstractSocket::ProxyNotFoundError:
        break;
    case QAbstractSocket::ProxyProtocolError:
        break;
    case QAbstractSocket::OperationError:
        break;
    case QAbstractSocket::SslInternalError:
        break;
    case QAbstractSocket::SslInvalidUserDataError:
        break;
    case QAbstractSocket::TemporaryError:
        break;
    case QAbstractSocket::UnknownSocketError:
        break;
    default:
        break;
    }
    qDebug() << QString("socket(%2,%3) error:"+m_csocket->errorString())
                .arg(netarg.ipStr).arg(netarg.port);
    m_NetState.linking = !disconnectMyHost();
}

void NetPort::checkLink()
{
    try{
        if(!m_NetState.linking){
            if(m_NetState.linkTime<mycachedata->getSec())
            {
                m_NetState.linking = connectMyHost();
                m_NetState.linkTime = mycachedata->getSec() + 10;
            }
        }else{
            if((m_NetState.heartTime+30)<mycachedata->getSec())
            {
                if(!m_NetState.ativity){
                    m_NetState.linking = !disconnectMyHost();
                }
                m_NetState.heartTime = mycachedata->getSec();
                m_NetState.ativity = false;
            }

        }
        if (m_NetState.linking&&(m_NetState.netPortStateTime<mycachedata->getSec()))
        {
            m_NetState.netPortStateTime = mycachedata->getSec() + netarg.timePush;
            TimeUp();
        }
    }catch(...){
        qDebug() << "NetPort::checkLink Exception";
    }
}

void NetPort::TimeUp()
{
    setPValue(-1, OnYX, m_NetState.linking?float(1.0):float(0.0));
    setPValue(-2, OnYX, m_NetState.m_wf ? float(1.0) : float(0.0));
    setPValue(-3, OnYX, m_NetState.m_rf ? float(1.0) : float(0.0));
    setPValue(-4, OnYX, m_NetState.m_tc ? float(1.0) : float(0.0));
    try{
        QMap<int, PInfo>::iterator it;
        unsigned int curT = mycachedata->getSec();
        for (it = addr_to_ids.begin();it!=addr_to_ids.end();it++)
        {
            bool sendf = false;
            //间隔10秒上送
            m_PMap_Mutex.lock();
            if ((it.value().sendTime + netarg.timePush) < curT)
            {
                it.value().sendTime = curT;
                sendf = true;
            }
            m_PMap_Mutex.unlock();
            if(sendf){
                setPValue(it.value().id, it.value().type, it.value().value);
            }
        }
    }catch(...){
        qDebug() << "NetPort::TimeUp Exception";
    }
}

void NetPort::checkReadyRead()
{
    if(m_NetState.linking&&NULL!=m_csocket){
        //主动触发读取
        m_csocket->waitForReadyRead(100);
    }
}

void NetPort::readData()
{
    try{
        if(NULL==m_csocket)
            return;
        if(QAbstractSocket::ConnectedState!=m_csocket->state()){
            return;
        }
//        qInfo()<<"ClientSocket::readData";
        while(m_csocket->bytesAvailable())
        {
            QByteArray vTemp;
            vTemp = m_csocket->readAll();
            m_NetState.ativity = true;
            if (vTemp.size() <= 0)
            {
                m_NetState.m_rf = false;
            }
            else
            {
                m_NetState.m_rf = true;
            }
//            qInfo()<<QString("readData(%1)").arg(vTemp.length());
            switch (netarg.type)
            {
            case 1:
            {
                try
                {
                    unsigned char *buff = (unsigned char*)vTemp.data();
                    int start = 0;
                    unsigned char ctype = 0;
                    for (int i = 0; i < vTemp.length(); i++)
                    {
                        //printf_s("%02X ",buff[i]);
                        if (buff[i] > 0xf0) {
                            if (buff[i] == 0xff) {
                                if (ctype) {
                                    ctype = 0;
                                    readCache((const unsigned char *)buff + start,i - start + 1);
                                    start = i + 1;
                                }
                            }
                            else {
                                ctype = buff[i];
                                start = i;
                            }
                        }
                    }
                    //printf_s("\n");
                    buff = NULL;
                    if (start < vTemp.length())
                    {
                        printf("Exception for vTemp.length()\n");
                    }
                }
                catch (...)
                {
                    qDebug() << QString("NetGatherDev Exception false!");
                }
                break;
            }
            case 2:
            {
                readCache((const unsigned char *)vTemp.data(),vTemp.length());
            }
                break;
            default:
                break;
            }
        }
    }catch(...){
        qDebug() << "NetPort::readData Exception";
    }
}

void NetPort::readCache(const unsigned char *bufdata,int buflen)
{
    switch (netarg.type)
    {
    case 1:
    {
        //反序列化
        unsigned char * pBuf = new unsigned char[buflen];
        int nLen = PFunc::uncode(bufdata, buflen, pBuf);
        msgResponse(pBuf, nLen);
        delete[] pBuf;
        pBuf = NULL;
    }
        break;
    case 2:
    {
        msgResponse((unsigned char *)bufdata, buflen);
    }
        break;
    default:
        break;
    }
}

void NetPort::msgResponse(unsigned char *buf, int len)
{
    try{
        QScriptValueList args;
        args << QString(QByteArray::fromRawData((const char*)buf,len).toHex());
        args << "NULL";
        myScr_Mutex.lock();
        QString retVal = myScr->myFunc("getReciveIDVAL",args).toString();
        myScr_Mutex.unlock();
        //qInfo()<<"ret="<<retVal;
        if(retVal.isEmpty())
            return;
    //    logNotify(retVal);
        QStringList idsDesc = retVal.split(';',QString::SkipEmptyParts);
        for(int i=0; i<idsDesc.size(); i++){
            QStringList ids = idsDesc.at(i).split(',',QString::SkipEmptyParts);
            if(2==ids.size()){
                int index = ids[0].toInt();
                float val = ids[1].toFloat();
                setValue(index,val);
            }
        }
    }catch(...){
        qDebug() << "NetPort::msgResponse Exception";
    }
}

void NetPort::setValue(int _addr, float _val)
{
    try{
        //查找与信息地址匹配的信息编号
        QMap<int, PInfo>::iterator it = addr_to_ids.find(_addr);
        if (it != addr_to_ids.end())
        {
            float _val_ = _val;
            if (it.value().type == OnYX)
            {
                _val_ = _val_ > 0 ? float(1) : float(0);
            }
            bool sendf = false;
            m_PMap_Mutex.lock();
            it.value().updateTime = mycachedata->getSec();
            //变化上送或间隔2秒上送
            if (abs(it.value().value - _val_) > FLIMIT
                || (it.value().sendTime + it.value().upInterval) < it.value().updateTime)
            {
                it.value().sendTime = it.value().updateTime;
                sendf = true;
            }
            it.value().value = _val_;//冗余记录
            m_PMap_Mutex.unlock();
            if(sendf){
                setPValue(it.value().id, it.value().type, _val_);
            }
        }
    }catch(...){
        qDebug() << "NetPort::setValue Exception";
    }
};

void NetPort::setPValue(int pid, PType type, float val)
{
    try{
        //查找与信息编号匹配的转发编号
        PTo _pto;
        if (mycachedata->getPTO(gatherID, pid, type, _pto))
        {
            WDS _wd(_pto.ptype, _pto.pid, val);
            ptr_ReceiveData->addWDS(_wd);
        }
    }catch(...){
        qDebug() << "NetPort::setPValue Exception";
    }
}

void NetPort::downControl(int _exetype, int _type, int _pid, float _val)
{
    try{
        qInfo()<<QString("downControl(%1):exetype(%2),type(%3),pid(%4),val(%5)")
                  .arg(gatherID).arg(_exetype).arg(_type).arg(_pid).arg(_val,0,'f',3);
        QMap<int,PInfo>::iterator it = id_to_addrs.find(_pid);
        if(it==id_to_addrs.end()){
            return;
        }
        if (_pid < 0)
        {
            controlGState(_exetype, _type, _pid, _val);
        }
        int allYXState = -1;
        if (1 == protodefs.allYXState)
        {
            allYXState = getAllYXVal(protodefs.YXGetValStart, protodefs.YXGetValEnd);
            //printf("allYXState=%02X\n", allYXState);
            qInfo() << QString("NetPort downControl time(%1), gatherID(%2), allYXState=%3")
                        .arg(PFunc::getCurrentTime())
                        .arg(gatherID).arg(allYXState);
        }
        QScriptValueList args;
        args<<_exetype << _type << it.value().addr << _val << allYXState;
        QString retVal = "";
        try{
            myScr_Mutex.lock();
            retVal = myScr->myFunc("getDownControl",args).toString();
            myScr_Mutex.unlock();
            qInfo() << "retVal="<<retVal;
        }catch(...){
            qWarning() << "call js do func getDownControl exp";
        }

        if(!retVal.isEmpty()){
            QStringList retList = retVal.split(',', QString::SkipEmptyParts);
            if(2!=retList.size()){
                qWarning() << QString("js to code inf(%1,%2,%3,%4) is error")
                            .arg(_exetype).arg(_type).arg(_pid).arg(_val,0,'f',2);
                return;
            }
            QString _cmd = retList.at(0);
            int checktype = retList.at(1).toInt();
            unsigned char buf[256] = { 0 };
            int buflen = 0;
    //        qInfo() << QString("%1,%2").arg(_cmd).arg(checktype);
            switch (checktype)
            {
            case 1:
            {
                int rlen = PFunc::string2bytes(_cmd.toStdString().c_str(), buf, _cmd.length());
                unsigned int crc = PFunc::crc16(buf, rlen);
                sprintf((char*)buf, "%s%02X%02X", _cmd.toStdString().c_str(), (crc & 0XFF), ((crc >> 8) & 0XFF));
                buflen = (int)strlen((char*)buf);
            }
                break;
            case 2:
            {
                buflen = PFunc::string2bytes(_cmd.toStdString().c_str(), buf, _cmd.length());
            }
                break;
            case 3:
            {
                unsigned char _buf[256] = { 0 };
                int rlen = PFunc::string2bytes(_cmd.toStdString().c_str(), _buf, _cmd.length());
                unsigned int crc = PFunc::crc16(_buf, rlen);
                sprintf((char*)_buf, "%s%02X%02X", _cmd.toStdString().c_str(), (crc & 0XFF), ((crc >> 8) & 0XFF));

                buflen = PFunc::string2bytes((const char*)_buf
                                                 , (unsigned char*)buf
                                                 , (int)strlen((char*)_buf));//hex to ascii
            }
                break;
            default:
                break;
            }
    //        for (int j = 0; j < buflen; j++) {
    //            printf("%02X", (unsigned char)buf[j]);
    //        }
    //        printf("\n");

            qInfo() << QString("NetPort downControl time(%1), gatherID(%2), getDownControl success, CMD(%3)")
                        .arg(PFunc::getCurrentTime())
                        .arg(gatherID).arg(_cmd);

//            writeData((unsigned char*)buf,buflen);
            AddCmd((unsigned char*)buf,buflen,false);
            if (1== protodefs.ykSetVal&&1==_type)
            {
                setValue(it.value().addr, _val);
                setPValue(_pid, OnYX, _val);
            }
        }else{
            qWarning()<<QString("NetPort downControl time(%1)"
                              ", gatherID(%2), exeType(%3),pID(%4),pType(%5),val(%6)"
                              ",getDownControl Error")
                      .arg(PFunc::getCurrentTime()).arg(gatherID)
                      .arg((int)_exetype).arg(_pid).arg((int)_type).arg(_val,0,'f',2);

    //        error_lua_count++;
    //        if (error_lua_count >= error_lua_max) {
    //            error_lua_count = 1;
    //            reSetlua();
    //        }
        }
    }catch(...){
        qDebug() << "NetPort::downControl Exception";
    }
}

void NetPort::writeMsg(unsigned char*buf,int buflen,bool u16f)
{
    if(u16f){
        //16进制字符转10进制
        unsigned char _buf[256] = { 0 };
        int rlen = PFunc::string2bytes((const char*)buf, _buf, buflen);
        writeData((unsigned char*)_buf,rlen);
    }else {
        writeData((unsigned char*)buf,buflen);
    }
//    m_NetState.m_tc = true;
}

void NetPort::writeData(unsigned char*buf,int buflen)
{
    try{
        if(NULL==m_csocket)
            return;
        if(QAbstractSocket::ConnectedState!=m_csocket->state()){
            return;
        }
        if (1 == netarg.type)//序列化
        {
            unsigned char _buf[256] = { 0 };
            int nLen = PFunc::code((unsigned char*)buf, buflen, _buf);
            m_csocket->write((const char*)_buf,nLen);
            bool ret = m_csocket->waitForBytesWritten();
            if(!ret){
                qWarning() << "net send cmd_code fail!";
                m_NetState.m_wf = false;
            }else{
                m_NetState.m_wf = true;
            }
        }else{
            m_csocket->write((const char*)buf,buflen);
            bool ret = m_csocket->waitForBytesWritten();
            if(!ret){
                qWarning() << "net send cmd fail!";
                m_NetState.m_wf = false;
            }else{
                m_NetState.m_wf = true;
            }
        }
    }catch(...){
        qDebug() << "NetPort::writeData Exception";
    }
}

int NetPort::getAllYXVal(int _start, int _end)
{
    int val = 0;
    try{
        QMap<int,PInfo>::iterator it = addr_to_ids.begin();
    //    std::map<int, PInfo>::iterator it = addr_pid_pinfos.begin();
        while (it!= addr_to_ids.end())
        {
            if (it.value().type == OnYX && it.key()>=_start && it.key()<=_end)
            {
                val += ((it.value().value>0?1:0) << (it.key()-_start));
            }
            it++;
        }
    }catch(...){
        qDebug() << "NetPort::getAllYXVal Exception";
    }

    return val;
};

void NetPort::controlGState(int _exetype, int _type, int _pid, float _val)
{
    qInfo() << QString("controlGState(%1,%2,%3,%4)")
                .arg(_exetype).arg(_type).arg(_pid).arg(_val,0,'f',2);
    ExeType _etype = (ExeType)_exetype;
    switch (_etype)
    {
    case OnGet:
    {
        switch (_pid)
        {
        case -1:
            setPValue(-1, OnYX, m_NetState.linking ? float(0.0) : float(1.0));
            break;
        case -2:
            setPValue(-2, OnYX, m_NetState.m_wf ? float(1.0) : float(0.0));
            break;
        case -3:
            setPValue(-3, OnYX, m_NetState.m_rf ? float(1.0) : float(0.0));
            break;
        case -4:
            setPValue(-4, OnYX, m_NetState.m_tc ? float(1.0) : float(0.0));
            break;
        default:
            break;
        }
    }
        break;
    case OnSet:
    {
        switch (_pid)
        {
        case -4:
            m_NetState.m_tc = _val > 0 ? true : false;
            setPValue(-4, OnYX, m_NetState.m_tc ? float(1.0) : float(0.0));
            break;
        default:
            break;
        }
    }
        break;
    case OnTran:
        break;
    case ExeTDef:
        break;
    default:
        break;
    }
}
